package com.dhnsoft.shortLink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhnsoft.shortLink.admin.common.biz.user.UserContext;
import com.dhnsoft.shortLink.admin.common.convention.result.Result;
import com.dhnsoft.shortLink.admin.dao.entity.GroupDO;
import com.dhnsoft.shortLink.admin.dao.mapper.GroupMapper;
import com.dhnsoft.shortLink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.dhnsoft.shortLink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.dhnsoft.shortLink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.dhnsoft.shortLink.admin.remote.ShortLinkRemoteService;
import com.dhnsoft.shortLink.admin.remote.dto.resp.ShortLinkCountQueryRespDTO;
import com.dhnsoft.shortLink.admin.service.GroupService;
import com.dhnsoft.shortLink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * ClassName: GroupServiceImpl
 * Package: com.dhnsoft.shortLink.admin.service.impl
 * Description:
 *
 * @Author dhn
 * @Create 2024/3/19 17:00
 * @Version 1.0
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    static ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
    };

    @Override
    public void saveGroup(String groupName) {
        //根据系统中上下文的用户名来查询分组中该用户名下的分组情况
        saveGroup(UserContext.getUsername(),groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        String gid;
        do {
            gid = RandomGenerator.generateRandom();
        }while (!hasGid(gid,username));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .name(groupName)
                .build();
        baseMapper.insert(groupDO);
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        //根据系统中上下文的用户名来查询分组中该用户名下的分组情况
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername,UserContext.getUsername()).eq(GroupDO::getDelFlag,0)
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        //通过匹配的wrapper来查询分组list集合
        List<GroupDO> groupDOS = baseMapper.selectList(queryWrapper);
        //根据gid列表去查询远程中台分组下短链接数量信息。
        Result<List<ShortLinkCountQueryRespDTO>> listResult =
                shortLinkRemoteService.listShortLinkCount(groupDOS.stream().map(GroupDO::getGid).toList());
        //将查询出来的用户下短链接分组信息转换成ShortLinkGroupRespDTO返回类格式
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOS = BeanUtil.copyToList(groupDOS, ShortLinkGroupRespDTO.class);
        //将查询出来每个gid下的短链接数量放入到ShortLinkGroupRespDTO中
        shortLinkGroupRespDTOS.forEach(each->{
            Optional<ShortLinkCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(each.getGid(), item.getGid()))
                    .findFirst();
            first.ifPresent(item->each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOS;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> update = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag,0);
        GroupDO groupDO = new GroupDO();
        groupDO.setGid(requestParam.getGid());
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,update);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupDO> update = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag,0);
        GroupDO groupDO = new GroupDO();
        groupDO.setGid(gid);
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO,update);
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each->{
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();

            LambdaUpdateWrapper<GroupDO> update = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO,update);
        });
    }

    private boolean hasGid(String gid,String username) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername,Optional.ofNullable(username).orElse( UserContext.getUsername()));
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO == null;
    }
}
